import { join } from 'node:path'
import { electronApp, is, optimizer } from '@electron-toolkit/utils'
import remote from '@electron/remote/main'
import { app, BrowserWindow, ipcMain, shell } from 'electron'
import icon from '../../resources/icon.png?asset'

const isProd = process.env.NODE_ENV === 'production' // 右键菜单需要

// ===================顶部菜单===================
// 自定义顶部菜单 因为涉及到文件加密 , 不能使用路径引入(TODO:打包引入的方式直接打包到内部)
// require('../../src/renderer/menu/topMenu.js')
const { Menu } = require('electron')

let menuTemplate = [
  // 一级菜单
  {
    label: '文件',
    // 二级菜单
    submenu: [
      {
        label: '新建',
        // 给菜单绑定点击事件
        click: () => { console.log('Ctrl + N') },
        // 给菜单绑定快捷键，可能有一些快捷键是电脑自带的快捷键，设置了可能不行 比如 ctrl + c
        accelerator: 'ctrl+n',
      },
      { label: '打开' },
      { label: '保存' },
    ],
  },
  {
    label: '编辑',
    submenu: [
      // 系统自带的快捷键需要借助 role 属性来绑定
      { label: '复制', role: 'copy' },
      // 使用分隔符不同label之间有一条横线
      { type: 'separator' },
      { label: '粘贴', role: 'paste',
      },
    ],
  },
//   {
//     label: '关于',
//     submenu: [
//     { label: '关于', role: 'about' },
//     { label: '工具栏', role: 'toggleDevTools' },
//     { label: '退出', accelerator: 'ctrl+Esc', role: 'quit' },
//     { label: '全屏', accelerator: 'ctrl+F11', role: 'togglefullscreen' },
//     ],
//   },
]
// 固定写法
let menuBuilder = Menu.buildFromTemplate(menuTemplate)
Menu.setApplicationMenu(menuBuilder)
// ===================顶部菜单结束===================

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    autoHideMenuBar: false, // false的情况要按下alt才显示顶部菜单
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation: false, // 右键菜单需要;(否则不能用require)
      enableRemoteModule: true, // 右键菜单需要
      nodeIntegration: true, // 允许执行远程代码,根据需要启用
      devTools: !isProd,
    },
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env.ELECTRON_RENDERER_URL) {
    mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL)
  }
  else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
  // 启动自动打开F12工具
  // let contents = mainWindow.webContents
  // contents.openDevTools()
  remote.initialize()
  remote.enable(mainWindow.webContents)
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()

  app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0)
      createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
